<template>
  <CommonPage>
    <NCard>
      <NForm
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="left"
        :label-width="140"
      >
        <NFormItem label="图片存放路径" path="image_path">
          <div style="display: flex; align-items: center; gap: 8px;">
            <NInput
              v-model:value="form.image_path"
              placeholder="请选择图片存放路径"
              readonly
              style="min-width: 500px"
            />
            <NButton @click="handleSelectPath('image')">选择目录</NButton>
          </div>
        </NFormItem>

        <NFormItem label="视频存放路径" path="video_path">
          <div style="display: flex; align-items: center; gap: 8px;">
            <NInput
              v-model:value="form.video_path"
              placeholder="请选择视频存放路径"
              readonly
              style="min-width: 500px"
            />
            <NButton @click="handleSelectPath('video')">选择目录</NButton>
          </div>
        </NFormItem>
      </NForm>

      <div mt-20>
        <NButton type="primary" :loading="loading" @click="handleSave">保存</NButton>
      </div>
    </NCard>
  </CommonPage>
</template>

<script setup>
import { h, onMounted, ref } from 'vue'
import { NButton, NInput, NFormItem, NForm, NCard } from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api/storage'
import { save, open } from '@tauri-apps/plugin-dialog'

defineOptions({ name: '存储路径设置' })

const loading = ref(false)
const formRef = ref(null)

const form = ref({
  image_path: '',
  video_path: '',
})

const rules = {
  image_path: {
    required: true,
    message: '请选择图片存放路径',
    trigger: ['blur'],
  },
  video_path: {
    required: true,
    message: '请选择视频存放路径',
    trigger: ['blur'],
  },
}

async function handleSelectPath(type) {
  try {
    const selectedPath = await open({
      directory: true,
      multiple: false,
      defaultPath: form.value[type === 'image' ? 'image_path' : 'video_path'] || undefined,
    })
    
    if (selectedPath) {
      if (type === 'image') {
        form.value.image_path = selectedPath
      } else {
        form.value.video_path = selectedPath
      }
    }
  } catch (error) {
    console.error('选择路径失败:', error)
    window.$message.error('选择路径失败')
  }
}

onMounted(async () => {
  try {
    const { data } = await api.getStorageConfig()
    if (data) {
      form.value = data
    }
  } catch (error) {
    window.$message.error('获取存储配置失败')
  }
})

async function handleSave() {
  try {
    loading.value = true
    await formRef.value?.validate()
    await api.updateStorageConfig(form.value)
    window.$message.success('保存成功')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script> 